<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

/**
 * This page prints all search's.
 *
 * @package   block_email_list
 * @author    Toni Mas <toni.mas@uib.dot.es>
 * @copyright 2009 by <toni.mas at uib dot es>
 * @license   The source code packaged with this file is Free Software, Copyright (C) 2009 by
 *            <toni.mas at uib dot es>.
 *            It's licensed under the AFFERO GENERAL PUBLIC LICENSE unless stated otherwise.
 *            You can get copies of the licenses here: http://www.affero.org/oagpl.html
 *            AFFERO GENERAL PUBLIC LICENSE is also included in the file called "COPYING".
 */
require_once('../../../config.php');
require_once($CFG->dirroot.'/blocks/email_list/email/lib.php');            // eMail library funcions

// For apply ajax and javascript functions.
require_once($CFG->libdir. '/ajax/ajaxlib.php');

// Search lib
require_once($CFG->libdir.'/searchlib.php');

// Advanced search form
require_once($CFG->dirroot.'/blocks/email_list/email/advanced_search_form.php');

$courseid    = optional_param('courseid', SITEID, PARAM_INT);     // Course ID
$folderid    = optional_param('folderid', 0, PARAM_INT);         // folder ID
$filterid    = optional_param('filterid', 0, PARAM_INT);            // filter ID

$page        = optional_param('page', 0, PARAM_INT);              // which page to show
$perpage     = optional_param('perpage', 10, PARAM_INT);          // how many per page

// Search words
$search      = optional_param('words', '', PARAM_TEXT);            // Text to search
$action      = optional_param('action', 0, PARAM_INT);        // Action


// If defined course to view
if (! $course = $DB->get_record('course', array('id' => $courseid))) {
    print_error('invalidcourseid', 'block_email_list');
}

require_login($course->id, false); // No autologin guest

if (! email_is_enabled_email_list($course->id)) {
    print_error('blocknotavailable', 'block_email_list');
}

// Add log for one course
add_to_log($courseid, 'email_list', 'search', 'view.php?id='.$courseid, 'View all mails of '.$course->shortname);

$context = context_course::instance($course->id);

$fullname = $DB->sql_fullname('u.firstname', 'u.lastname');
$like = $DB->sql_like($fullname,':searchtext1',false,false);

/// Print the page header
if (has_capability('block/email_list:editsettings', $context)) {
    $preferencesbutton = email_get_preferences_button($courseid);
    $PAGE->set_button($preferencesbutton);
}

$stremail  = get_string('name', 'block_email_list');

if ( $search == get_string('searchtext', 'block_email_list') or $search == '' ) {
    $strsearch = get_string('advancedsearch', 'search');
} else {
    $strsearch = get_string('search', 'search');
}

$PAGE->set_title("$course->shortname: $stremail: $strsearch");
$PAGE->set_heading("$course->fullname");
$PAGE->set_cacheable(true);
$PAGE->set_url('/blocks/email_list/email/search.php?courseid='.$course->id.'&amp;action='.$action);

$PAGE->navbar->add(get_string('nameplural', 'block_email_list'), 'index.php?id='.$course->id);
$PAGE->navbar->add($strsearch);
$PAGE->requires->css('/blocks/email_list/email/email.css');
$PAGE->requires->css('/blocks/email_list/email/treemenu.css');
$PAGE->requires->css('/blocks/email_list/email/tree.css');
$PAGE->requires->js('/blocks/email_list/email/treemenu.js');
$PAGE->requires->js('/blocks/email_list/email/email.js');

echo $OUTPUT->header();

// Options for new mail and new folder
$options = new stdClass();
$options->id = $courseid;
$options->folderid = $folderid;
$options->filterid = $filterid;

/// Print the main part of the page

// Print principal table. This have 2 columns . . .  and possibility to add right column.
echo '<table id="layout-table" style="width:100%">
              <tr>';

$search_empty = ($search == get_string('searchtext', 'block_email_list') || $search == '');

// Print "blocks" of this account
echo '<td style="width: 180px;vertical-align:top;" id="left-column">';
email_printblocks($USER->id, $courseid, $search_empty);

// Close left column
echo '</td>';

// Print principal column
echo '<td id="middle-column">';

// Print middle table
echo $OUTPUT->heading($strsearch, 2, 'headingblock header');

// Create advanced search form
$advancedsearch = new advanced_search_form();

if ($search_empty && (! $advancedsearch->is_submitted())) {

    if (! $action) {
        $OUTPUT->notification(get_string('emptysearch', 'block_email_list'));
        $OUTPUT->notification(get_string('wantadvancedsearch', 'block_email_list'), 'notifysuccess');
    }

    // Print advanced search form
    $advancedsearch->display();

} else if ($advancedsearch->is_cancelled()) {

    // Cancelled form
    redirect($CFG->wwwroot.'/blocks/email_list/email/index.php?id='.$courseid, '', 1);

} else if ($data = $advancedsearch->get_data()) {

    /// Advanced Search by:
    ///		- Folders
    ///		- Course
    ///		- From
    ///		- To
    ///		- Subject
    ///		- Body
    ///
    ///		And / Or


    $select = 'SELECT m.*, sndr.firstname, sndr.lastname, m.userid as writer';

    $from = 'FROM '.$CFG->prefix.'block_email_list_mail AS m '
                .'JOIN '.$CFG->prefix.'block_email_list_foldermail AS fm ON fm.mailid = m.id '
                .'LEFT JOIN '.$CFG->prefix.'block_email_list_send AS s ON s.mailid = m.id AND s.course = m.course '
                .'LEFT JOIN '.$CFG->prefix.'user AS sndr ON sndr.id = m.userid ';

    $searchsql = array();
    $values = array();

    //recipient search
    if (!empty($data->to)) {
        $searchtext = trim($data->to);
        if ($searchtext !== '') {
            $fullname = $DB->sql_fullname('reci.firstname', 'reci.lastname');
            $searchsql['recipient'] = '(s.type != "bcc" AND reci.id = s.userid '
                            .'AND ('.$DB->sql_like('reci.firstname','?',false,false).' '
                            .'OR '.$DB->sql_like('reci.lastname','?',false,false).' '
                            .'OR ('.$DB->sql_like($fullname,'?',false,false).')))';
            $values[] = '%'.$searchtext.'%';
            $values[] = '%'.$searchtext.'%';
            $values[] = '%'.$searchtext.'%';
            $from .= 'LEFT JOIN '.$CFG->prefix.'user AS reci ON reci.id = s.userid ';
        }
    }

    //sender search
    if (!empty($data->from)) {
        $searchtext = trim($data->from);
        if ($searchtext !== '') {
            $fullname = $DB->sql_fullname('sndr.firstname', 'sndr.lastname');
            $searchsql['sender'] = '(sndr.id = m.userid '
                            .'AND ('.$DB->sql_like('sndr.firstname','?',false,false).' '
                            .'OR '.$DB->sql_like('sndr.lastname','?',false,false).' '
                            .'OR ('.$DB->sql_like($fullname,'?',false,false).')))';
            $values[] = '%'.$searchtext.'%';
            $values[] = '%'.$searchtext.'%';
            $values[] = '%'.$searchtext.'%';
        }
    }

    //subject search
    if (!empty($data->subject)) {
        $searchstring = str_replace( "\\\"", "\"", $data->subject);
        $parser = new search_parser();
        $lexer = new search_lexer($parser);

        if ($lexer->parse($searchstring)) {

            $parsearray = $parser->get_parsed_array();
            $subjectparts = array();
            if (!empty($parsearray) && is_array($parsearray)) {
                foreach ($parsearray as $sterm) {
                    $subjectparts[] = '('.$DB->sql_like('m.subject','?',false,false).')';
                    $values[] = '%'.$sterm->getValue().'%';
                }
            }

            if (!empty($subjectparts)) {
                $searchsql['subject'] = '('.implode(' '.$data->connector.' ', $subjectparts).')';
            }
        }
    }

    //body search
    if (!empty($data->body)) {
        $searchstring = str_replace( "\\\"", "\"", $data->body);
        $parser = new search_parser();
        $lexer = new search_lexer($parser);

        if ($lexer->parse($searchstring)) {

            $parsearray = $parser->get_parsed_array();
            $bodyparts = array();
            if (!empty($parsearray) && is_array($parsearray)) {
                foreach ($parsearray as $sterm) {
                    $bodyparts[] = '('.$DB->sql_like('m.body','?',false,false).')';
                    $values[] = '%'.$sterm->getValue().'%';
                }
            }

            if (!empty($bodyparts)) {
                $searchsql['body'] = '('.implode(' '.$data->connector.' ', $bodyparts).')';
            }
        }
    }

    // Begin assembling WHERE
    $wheresql = array();
    if (!empty($searchsql) && is_array($searchsql)) {
        $wheresql[] = '('.implode(' '.$data->connector.' ',$searchsql).')';
    }

    //COURSE RESTRICTION
    $wheresql[] = '(m.course = '.$courseid.')';

    //folders restriction
    //ensure folders are restricted to user's folders
    if (empty($data->folders) || !is_array($data->folders)) {
        print_error('nosearchfolders', 'block_email_list');
    }
    $folders = email_get_root_folders($USER->id);
    $folderids = array();
    foreach ($folders as $folder) {
        $folderids[] = $folder->id;
        $subfolders = email_get_subfolders($folder->id);
        if (!empty($subfolders) && is_array($subfolders)) {
            foreach ($subfolders as $sfolder) {
                $folderids[] = $sfolder->id;
            }
        }
    }
    $wherefolders = array_intersect($folderids,array_keys($data->folders));
    $wheresql[] = '( fm.folderid IN ('.implode(',',$wherefolders).' ) )';

    //group by
    $groupby = ' GROUP BY m.id';

    //assemble full sql
    $sql = $select.' '.$from.' WHERE '.implode(' AND ',$wheresql).' '.$groupby;
    if (! $searchmails = $DB->get_records_sql($sql, $values) ) {
        debugging('Empty advanced search for next SQL stament: '.$sql, DEBUG_DEVELOPER);
    }

    $advancedsearch->display();

    if (!empty($searchmails)) {
        $OUTPUT->notification(get_string('searchword', 'block_email_list'), 'notifysuccess');
    }

    // Show mails searched
    echo email_showmails($USER->id, '', $page, $perpage, $options, true, $searchmails);

} else {

    // Simple search
    $select = 'SELECT m.*, u.firstname,u.lastname, m.userid as writer';

    $from    = ' FROM {user} u, {block_email_list_mail} m, {block_email_list_send} s,'
            . ' {block_email_list_foldermail} fm';

    $values = array();

    // FOLDERS
    $wherefolders = '';
    $folders = email_get_root_folders($USER->id, false);

    if ( ! empty( $folders) ) {
        $wherefolders .= ' AND ( ';
        $i = 0;

        foreach ( $folders as $folder ) {
            $wherefolders .= ($i > 0) ? ' OR fm.folderid = :folderid'.$i.' ' : ' fm.folderid = :folderid'.$i.' '; // Select this folder
            $values['folderid'.$i] = $folder->id;
            $i++;

            // Now, get all subfolders it
            $subfolders = email_get_subfolders($folder->id);

            // If subfolders
            if ( $subfolders ) {

                foreach ( $subfolders as $subfolder ) {
                    $wherefolders .= ($i > 0) ? ' OR fm.folderid = :subfolderid'.$i.' ': ' fm.folderid = :subfolderid'.$i.' '; // Select this folder
                    $values['subfolderid'.$i] = $folder->id;
                    $i++;
                }
            }
        }
        $wherefolders .= ' ) ';
    } else {
        print_error('nosearchfolders', 'block_email_list');
    }

    $groupby = ' GROUP BY m.id, m.userid, m.course, m.subject, m.timecreated, m.body, u.firstname, u.lastname, m.respondedid';

    // TO
    $myto = ' m.userid = :userid AND m.userid = u.id ';
    $values['userid'] = $USER->id;

    $searchto   = '';
    $searchfrom = '';
    $sqlsubject = '';
    $sqlbody = '';

    if (! empty($search)) {
        $searchtext = trim($search);

        if ($searchtext !== '') {   // Search for a subset of remaining users
            // These 3 lines do nothing.  Check whether "to" field is actually being searched
            $fullname  = $DB->sql_fullname('u.firstname', 'u.lastname');
            $like1 = $DB->sql_like($fullname,':searchtext',false,false);
            $searchto = " AND ($like1) ";
            $values['searchtext'] = "%$searchtext%";

            $fullname  = $DB->sql_fullname();
            $like2 = $DB->sql_like($fullname,':searchtext',false,false);
            $searchfrom = " OR ($like2) )";
        }

        $searchstring = str_replace('\"', '"', $search);
        $parser = new search_parser();
        $lexer = new search_lexer($parser);

        if ($lexer->parse($searchstring)) {
            $parsearray = $parser->get_parsed_array();

            $subjectparts = array();
            $bodyparts = array();

            if (!empty($parsearray)) {
                // Go through each search term to build up the SQL fragments
                foreach ($parsearray as $sterm) {
                    $subjectparts[] = "(m.subject $LIKE '%{$sterm->value}%')";
                    $bodyparts[] = "(m.body $LIKE '%{$sterm->value}%')";
                }
            }

            if (!empty($subjectparts)) {
                $sqlsubject = implode(' OR ', $subjectparts);
            }

            if (!empty($bodyparts)) {
                $sqlbody = implode(' OR ', $bodyparts);
            }

            $sqlsubjectbody = (! empty($sqlsubject) ) ? " AND ( $sqlsubject OR $sqlbody " : ' AND '.$sqlbody;
        }

    } else if (!empty($sqlsubject)) {
        $sqlsubjectbody = ' AND '.$sqlsubject;
    } else {
        $sqlsubjectbody = '';
    }

    $sqlcourse = ' AND s.course = m.course AND m.course = :mcourse AND s.course = :scourse ';
    $values['mcourse'] = $courseid;
    $values['scourse'] = $courseid;

    // README: If you can search by to, this simple search mode don't get this results, you use advanced search.
    // Only search by: Folder and ( Subject or Body or From).

    $sql = '';

    $sql .= $select.$from. ' WHERE fm.mailid = m.id '.
                    ' AND m.userid = u.id '. // Allways I'm searching writer ... show Select fields
                    ' AND s.mailid = m.id '. // Allways searching one mail ... apply join
    $wherefolders.
    $sqlcourse.
    $sqlsubjectbody.
    $searchfrom.
                    ' AND (m.userid = :muserid OR (s.userid = :suserid AND s.mailid = m.id)) '.
    $groupby;
    $values['muserid'] = $USER->id;
    $values['suserid'] = $USER->id;

    if (! $searchmails = $DB->get_records_sql($sql, $values)) {
        debugging('Empty simple search for next SQL stament: '. $sql, DEBUG_DEVELOPER);
    }

    $advancedsearch->display();

    echo $OUTPUT->notification(get_string('searchword', 'block_email_list'), 'notifysuccess');

    // Show mails searched
    echo email_showmails($USER->id, '', $page, $perpage, $options, true, $searchmails);
}

// Close principal column
echo '</td>';

// Close table
echo '</tr> </table>';

echo $OUTPUT->footer();
